package com.verisette.ncos.web.accesscontrol.listener;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import org.apache.log4j.Logger;

import org.corp.agi.basic.web.accesscontrol.listener.LogoutSessionListener;
import org.corp.agi.common.util.BeanContextFactory;
import org.corp.agi.service.bean.ServiceRequest;
import org.corp.agi.service.bean.ServiceResponse;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.web.constant.WebConstant;
import com.verisette.ncos.service.accesscontrol.gateway.CustomAccessControlService;

public class CustomLogoutSessionListener {
	private int sessionCount;
	private Logger logger = Logger.getLogger(LogoutSessionListener.class);

	public CustomLogoutSessionListener() {
	    this.sessionCount = 0;
	}

	public void sessionCreated(HttpSessionEvent se) {

		// 15 Min Expire
		HttpSession session = se.getSession();
	    //session.setMaxInactiveInterval(DataSupporter.getSessionTimeOutMinutes()*60);
	    
	    if(logger.isInfoEnabled())
	    {
		    synchronized (this) {
		      sessionCount++;
		    }
		    String id = session.getId();
		    Date now = new Date();
		    String message = new StringBuffer("\nNew Session created on ").append(
		        now.toString()).append("\nID::").append(id).append("\n")
		        .append("There are now ").append("" + sessionCount).append(
		            " live sessions in the application.").toString();

		    logger.info(message);
	    }

	}

	public void sessionDestroyed(HttpSessionEvent se) {

		HttpSession session = se.getSession();
	    String id = session.getId();
	    
	    CustomAccessControlService accessControlService = (CustomAccessControlService)BeanContextFactory.getBean("customAccessControlServiceImpl");
		
		ServiceRequest<UserBean> serviceRequest = new ServiceRequest<UserBean>();
		serviceRequest.setSessionID(id);
        		
		UserBean masUser = (UserBean) se.getSession().getAttribute(WebConstant.SESSION_USERBEAN_KEY);
		serviceRequest.setValueObject(masUser);
        
        ServiceResponse<UserBean> response = accessControlService.customLogout(serviceRequest);
		
		if(logger.isInfoEnabled())
	    {
		    synchronized (this) {
		      --sessionCount;
		    }
		    String message = new StringBuffer("\nSession destroyed"
		        + "\nValue of destroyed session ID is::").append("" + id).append(
		        "\n").append("There are now ").append("" + sessionCount)
		        .append(" live sessions in the application.").toString();
		    
		    logger.info(message);
	    }

	}
}
